package org.zjx.resource;

import com.alibaba.fastjson2.JSON;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;


/**
 * 资源文件加密
 */
public class ResourceEncryptor {
    public static final String ALGORITHM = "AES";

    // 生成密钥
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        return keyGenerator.generateKey();
    }

    // 使用指定的密钥字符串生成 SecretKey
    public static SecretKey getKeyFromString(String keyStr) {
        byte[] keyBytes = keyStr.getBytes(StandardCharsets.UTF_8);
        // 确保密钥长度是 16 字节 (128 位)，根据 AES 的要求
        byte[] key = new byte[16];
        System.arraycopy(keyBytes, 0, key, 0, Math.min(keyBytes.length, 16));
        return new SecretKeySpec(key, "AES");
    }

    // 加密并保存对象到文件
    public static void encryptAndSaveToFile(Object object, String filePath, SecretKey key) throws Exception {
        // 将对象转为 JSON 字符串

        String json = JSON.toJSONString(object);

        // 加密 JSON 字符串的字节数据
        byte[] encryptedData = encrypt(json.getBytes(StandardCharsets.UTF_8), key);

        //文件不存在时，创建文件
        File file = new File(filePath);
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();  // Creates the necessary directories
        }

        // 将加密数据保存到文件
        try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
            fileOutputStream.write(encryptedData); // 直接写入加密数据
        }
    }

    // 加密方法
    private static byte[] encrypt(byte[] data, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    // 获取 Cipher 实例
    private static Cipher getCipher(int mode, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(mode, key);
        return cipher;
    }


}
